package com.x.netty.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.File;
import java.io.FileInputStream;

/**
 * @Author _G5niusX
 * @Date 2018/5/18 22:28
 */
public class NettyClient {
    final private String host;
    final private int port;

    public NettyClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    private void connect() throws InterruptedException {
        EventLoopGroup eventExecutors = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventExecutors).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                    @Override
                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                        File file = new File("F://favicon.ico");
                        FileInputStream fileInputStream = new FileInputStream(file);
                        FileRegion fileRegion = new DefaultFileRegion(fileInputStream.getChannel(), 0, file.length());
                        System.out.println("length = " + file.length());
                        ctx.writeAndFlush(fileRegion).addListener((ChannelFutureListener) future -> {
                            if (future.isSuccess()) {
                                System.out.println("传输成功....");
                            }
                        });
                    }
                });
            }
        });
        ChannelFuture sync = bootstrap.connect(host, port).sync();
        sync.channel().closeFuture().sync();
    }

    public static void main(String[] args) throws InterruptedException {
        new NettyClient("127.0.0.1", 9000).connect();
        ;
    }
}
